<template>
  <div class="p-6">
    <!-- 搜索/筛选 -->
    <a-space class="mb-4">
      <a-input v-model:value="filters.keyword" placeholder="搜索接口名/路径" style="width: 250px" />
      <a-select v-model:value="filters.status" placeholder="状态" style="width: 120px" allow-clear>
        <a-select-option value="active">启用</a-select-option>
        <a-select-option value="disabled">禁用</a-select-option>
      </a-select>
      <a-button type="primary" @click="fetchApisFromServer">搜索</a-button>
    </a-space>

    <!-- 批量操作 -->
    <a-space class="mb-2">
      <a-button type="primary" @click="batchEnable" :disabled="!selectedApis.length">批量启用</a-button>
      <a-button type="default" @click="batchDisable" :disabled="!selectedApis.length">批量禁用</a-button>
      <a-button type="dashed" danger @click="batchDelete" :disabled="!selectedApis.length">批量删除</a-button>
    </a-space>

    <!-- 接口表格 -->
    <a-table :columns="columns" :data-source="filteredApis" row-key="resourceId" :row-selection="rowSelection" bordered
      :scroll="{ x: 900 }">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'isActive'">
          <a-tag :color="record.isActive === 'active' ? 'green' : 'red'">
            {{ record.isActive === 'active' ? '启用' : '禁用' }}
          </a-tag>
        </template>

         <template v-else-if="column.key === 'permissionScope'">
          <a-tag :color="record.permissionScope === 'Local' ? 'orange' : 'blue'">
            {{ record.permissionScope === 'Local' ? '本地验证' : '权限中心' }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click.stop="openDetails(record)">
              详情
            </a-button>

            <a-button type="link" @click.stop="openBindPermissions(record)">{{ record.permissionKey ? '更改权限' : '绑定权限'
            }}</a-button>
          </a-space>
        </template>

        <template v-else>
          {{ record[column.dataIndex] }}
        </template>
      </template>
    </a-table>

    <!-- 接口详情侧边栏 -->
    <a-drawer title="接口详情" :visible="showDetails" :width="400" @close="showDetails = false" placement="right">
      <div v-if="selectedApi">
        <p><strong>接口Code: </strong>{{ selectedApi.resourceId }}</p>
        <p><strong>权限key: </strong>{{ selectedApi.permissionKey }}</p>
        <p><strong>所在服务名称: </strong>{{ selectedApi.fromServiceName }}</p>

        <!-- 验证方式 -->
        <p>
          <strong>验证方式：</strong>
          <a-select v-model:value="selectedApi.permissionScope" style="width: 120px" @change="updatePermissionScope">
            <a-select-option value="Local">Local</a-select-option>
            <a-select-option value="Centralized">Centralized</a-select-option>
          </a-select>
        </p>

        <!-- 状态 + 操作按钮 -->
        <p>
          <strong>状态：</strong>
          <a-tag :color="selectedApi.isActive === 'active' ? 'green' : 'red'">
            {{ selectedApi.isActive === 'active' ? '启用' : '禁用' }}
          </a-tag>
          <a-button size="small" type="link" @click="toggleStatus(selectedApi)">
            {{ selectedApi.isActive === 'active' ? '禁用' : '启用' }}
          </a-button>
        </p>

        <p><strong>接口说明：</strong>{{ selectedApi.description || '无' }}</p>
      </div>
    </a-drawer>

    <!-- 权限绑定侧边栏 -->
    <a-drawer title="绑定权限" :visible="showBindDrawer" :width="600" @close="showBindDrawer = false">
      <div v-if="selectedApi">
        <!-- 接口信息 -->
        <a-card title="接口信息" class="mb-4">
          <p><strong>接口ID：</strong>{{ selectedApi.resourceId }}</p>
          <p><strong>描述：</strong>{{ selectedApi.description || '无' }}</p>
          <p><strong>状态：</strong>
            <a-tag :color="selectedApi.isActive === 'active' ? 'green' : 'red'">
              {{ selectedApi.isActive === 'active' ? '启用' : '禁用' }}
            </a-tag>
          </p>
          <p><strong>权限Key：</strong>{{ selectedApi.permissionKey ? selectedApi.permissionKey : '无' }}</p>
        </a-card>

        <!-- 权限表格（单选模式） -->
        <a-table :columns="permissionColumns" :data-source="permissions" row-key="permissionId" bordered
          :row-selection="permissionRowSelection" />

        <!-- 新增权限 -->
        <a-space class="mt-4">
          <a-input v-model:value="newPermissionName" placeholder="权限名称" />
          <a-input v-model:value="newPermissionDescription" placeholder="权限描述" />
          <a-button type="primary" @click="addPermission">新增权限</a-button>
        </a-space>

        <!-- 确认绑定 -->
        <a-button v-if="!selectedApi?.permissionKey" type="primary" class="mt-4" @click="bindSelectedPermission"
          :disabled="!selectedPermissionId">
          绑定权限
        </a-button>

        <a-button v-else type="primary" class="mt-4" @click="updateApiPermission" :disabled="!selectedPermissionId">
          更改权限
        </a-button>

      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { apiFetch } from '@/utils/request'
import { message } from 'ant-design-vue'

interface Api {
  resourceId: string
  permissionKey: string
  fromServiceName: string
  isActive: string
  description: string
  permissionScope: string
}

interface Permission {
  permissionId: string
  permissionKey: string
  description: string
}

interface ApiResponse<T> {
  isSuccess: boolean
  errors: string[]
  data: T
}

const identityurl = import.meta.env.VITE_API_IDENTITY

const apis = ref<Api[]>([])
const filters = ref({ keyword: '', status: '' })
const selectedApis = ref<string[]>([])
const showDetails = ref(false)
const selectedApi = ref<Api | null>(null)

const showBindDrawer = ref(false)
const permissions = ref<Permission[]>([])
const newPermissionName = ref('')
const newPermissionDescription = ref('')
const selectedPermissionId = ref<string | null>(null)

// ------------------- 表格 & 过滤 -------------------
const columns = [
  { title: '接口Code', dataIndex: 'resourceId', key: 'resourceId' },
  { title: '接口说明', dataIndex: 'description', key: 'description' },
  { title: '验证方式', dataIndex: 'permissionScope', key: 'permissionScope' },
  { title: '状态', dataIndex: 'isActive', key: 'isActive' },
  { title: '所在服务名称', dataIndex: 'fromServiceName', key: 'fromServiceName' },
  { title: '权限key', dataIndex: 'permissionKey', key: 'permissionKey' },
  { title: '操作', key: 'action' }
]

const filteredApis = computed(() =>
  apis.value.filter(a => {
    const matchKeyword = !filters.value.keyword || a.description.includes(filters.value.keyword) || a.fromServiceName.includes(filters.value.keyword)
    const matchStatus = !filters.value.status || a.isActive === filters.value.status
    return matchKeyword && matchStatus
  })
)

const rowSelection = computed(() => ({
  selectedRowKeys: selectedApis.value,
  onChange: (keys: string[]) => selectedApis.value = keys
}))

const permissionColumns = [
  { title: '权限名', dataIndex: 'permissionKey', key: 'permissionKey' },
  { title: '描述', dataIndex: 'description', key: 'description' }
]

const permissionRowSelection = computed(() => ({
  type: 'radio',
  selectedRowKeys: selectedPermissionId.value ? [selectedPermissionId.value] : [],
  onChange: (keys: string[]) => selectedPermissionId.value = keys[0] || null
}))

// ------------------- 生命周期 -------------------
onMounted(() => fetchApisFromServer())

// ------------------- API 请求 -------------------
async function fetchApisFromServer() {
  const data = await apiFetch<{ resourceId: string, permissionKey: string, fromServiceName: string, isActive: boolean, description: string, permissionScope: string }[]>(`${identityurl}/api/permissionbindings`, { method: 'GET' })
  apis.value = data.map(a => ({
    resourceId: a.resourceId,
    permissionKey: a.permissionKey,
    fromServiceName: a.fromServiceName,
    isActive: a.isActive ? 'active' : 'disabled',
    description: a.description,
    permissionScope: a.permissionScope
  }))
}

async function fetchPermissions() {
  if (!selectedApi.value) return
  const response = await apiFetch<ApiResponse<{ id: string; name: string; description: string }[]>>(`${identityurl}/api/permissions/unboundApi`)
  permissions.value = response.data.map(p => ({
    permissionId: p.id,
    permissionKey: p.name,
    description: p.description
  }))
}

// ------------------- 操作 -------------------
function openBindPermissions(api: Api) {
  selectedApi.value = api
  showBindDrawer.value = true
  selectedPermissionId.value = null
  fetchPermissions()
}

function openDetails(api: Api) {
  selectedApi.value = api
  showDetails.value = true
}

async function toggleStatus(api: Api) {
  const active = api.isActive === 'active' ? 'disabled' : 'active'
  const result = await apiFetch<ApiResponse<{ isActive: boolean }>>(`${identityurl}/api/permissionbindings/isActive`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ resourceId: api.resourceId, isActive: active === 'active' })
  })
  if (result.isSuccess) {
    api.isActive = active
  }
  else {
    message.error(result.errors || '操作失败 ❌')
  }
}


function batchEnable() {
  apis.value.forEach(a => selectedApis.value.includes(a.resourceId) && (a.isActive = 'active'))
}

function batchDisable() {
  apis.value.forEach(a => selectedApis.value.includes(a.resourceId) && (a.isActive = 'disabled'))
}

function batchDelete() {
  apis.value = apis.value.filter(a => !selectedApis.value.includes(a.resourceId))
  selectedApis.value = []
}

// ------------------- 权限绑定 -------------------
async function addPermission() {
  if (!newPermissionName.value.trim()) return
  const newPerm = await apiFetch<Permission>(`${identityurl}/api/permissions`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ key: newPermissionName.value, name: newPermissionName.value, description: newPermissionDescription.value })
  })
  permissions.value.push(newPerm)
  newPermissionName.value = ''
  newPermissionDescription.value = ''

  await fetchPermissions() // 重新拉取权限列表
}

async function bindSelectedPermission() {
  if (!selectedApi.value || !selectedPermissionId.value) return

  const res = await apiFetch<ApiResponse<{ isSuccess: boolean }>>(`${identityurl}/api/permissionbindings`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ resourceId: selectedApi.value.resourceId, permissionId: selectedPermissionId.value })
  })

  if (res.isSuccess) {
    const permission = permissions.value.find(p => p.permissionId === selectedPermissionId.value)
    const apiIndex = apis.value.findIndex(a => a.resourceId === selectedApi.value?.resourceId)
    if (apiIndex !== -1) apis.value[apiIndex].permissionKey = permission?.permissionKey || ''
    showBindDrawer.value = false
  } else {
    message.error(res.errors || '操作失败 ❌')
  }
}

async function updateApiPermission() {
  if (!selectedApi.value || !selectedPermissionId.value) return

  const res = await apiFetch<ApiResponse<{ isSuccess: boolean }>>(`${identityurl}/api/permissionbindings/Update`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ resourceId: selectedApi.value.resourceId, permissionId: selectedPermissionId.value })
  })

  if (res.isSuccess) {
    const permission = permissions.value.find(p => p.permissionId === selectedPermissionId.value)
    const apiIndex = apis.value.findIndex(a => a.resourceId === selectedApi.value?.resourceId)
    if (apiIndex !== -1) apis.value[apiIndex].permissionKey = permission?.permissionKey || ''
    showBindDrawer.value = false
  } else {
    message.error(res.errors || '操作失败 ❌')
  }
}

async function updatePermissionScope(value: string) {
  if (!selectedApi.value) return
  const result = await apiFetch<ApiResponse<{ data: string }>>(
    `${identityurl}/api/permissionbindings/scope`,
    {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        resourceId: selectedApi.value.resourceId,
        PermissionScopeValue: value
      })
    }
  )

  if (result.isSuccess) {
    message.success('验证方式已更新 ✅')
  } else {
    message.error(result.errors || '更新验证方式失败 ❌')
  }
}
</script>
